package com.xuecheng.orders.interfaces.web;

import com.xuecheng.orders.application.service.XcOrderApplication;
import com.xuecheng.orders.domain.model.vo.req.OrderCreateCmd;
import com.xuecheng.orders.domain.model.vo.resp.PayRecordResp;
import com.xuecheng.orders.infrastructure.config.AlipayConfig;
import com.xuecheng.orders.infrastructure.util.SecurityUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author itcast
 */
@Slf4j
@RestController
public class XcOrdersApi {

    @Autowired
    private XcOrderApplication xcOrderApplication;

    @ApiOperation("生成支付二维码")
    @PostMapping("/generatepaycode")
    public PayRecordResp generatePayCode(@Validated @RequestBody OrderCreateCmd orderCreateCmd){
        Long userId = SecurityUtil.getUser().getId();

        return xcOrderApplication.createOrder(userId, orderCreateCmd);
    }

    @ApiOperation("扫码生成支付表单")
    @GetMapping("/requestpay")
    public void requestPay(@RequestParam("payNo") String payNo,
                           HttpServletResponse httpServletResponse) throws IOException {
        String form = xcOrderApplication.requestPay(payNo);

        httpServletResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpServletResponse.getWriter().write(form);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    @ApiOperation("接收支付结果异步通知")
    @PostMapping("/receivenotify")
    public void receivenotify(HttpServletRequest request, HttpServletResponse out){
        System.out.println("异步通知");

       xcOrderApplication.receivenotify(request.getParameterMap());
    }

}
